package com.ruoyi.web.controller.system

import com.ruoyi.common.annotation.Log
import com.ruoyi.common.core.controller.BaseController
import com.ruoyi.common.core.domain.AjaxResult
import com.ruoyi.common.core.domain.entity.SysDept
import com.ruoyi.common.core.domain.entity.SysRole
import com.ruoyi.common.core.domain.entity.SysUser
import com.ruoyi.common.core.domain.model.LoginUser
import com.ruoyi.common.core.page.TableDataInfo
import com.ruoyi.common.enums.BusinessType
import com.ruoyi.common.utils.MyStringUtils
import com.ruoyi.common.utils.poi.ExcelUtil
import com.ruoyi.framework.web.service.SysPermissionService
import com.ruoyi.framework.web.service.TokenService
import com.ruoyi.system.domain.SysUserRole
import com.ruoyi.system.service.ISysDeptService
import com.ruoyi.system.service.ISysRoleService
import com.ruoyi.system.service.ISysUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import javax.servlet.http.HttpServletResponse

/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
open class SysRoleController : BaseController() {
    @Autowired
    private lateinit var roleService: ISysRoleService
    @Autowired
    private lateinit var tokenService: TokenService
    @Autowired
    private lateinit var permissionService: SysPermissionService
    @Autowired
    private lateinit var userService: ISysUserService
   @Autowired
    private lateinit var deptService: ISysDeptService

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
   open fun list(role: SysRole): TableDataInfo {
        startPage()
        val list = roleService.selectRoleList(role)
        return getDataTable(list)
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/export")
    open  fun export(response: HttpServletResponse, role: SysRole) {
        val list = roleService.selectRoleList(role)
        val util: ExcelUtil<SysRole> = ExcelUtil(SysRole::class.java)
        util.exportExcel(response, list, "角色数据")
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = ["/{roleId}"])
    open  fun getInfo(@PathVariable roleId: Long?): AjaxResult {
        roleService.checkRoleDataScope(roleId)
        return success(roleService.selectRoleById(roleId))
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    open  fun add(@Validated @RequestBody role: SysRole): AjaxResult {
        if (!roleService.checkRoleNameUnique(role)) {
            return error("新增角色'" + role.roleName + "'失败，角色名称已存在")
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return error("新增角色'" + role.roleName + "'失败，角色权限已存在")
        }
        role.createBy=username
        return toAjax(roleService.insertRole(role))
    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    open  fun edit(@Validated @RequestBody role: SysRole): AjaxResult {
        roleService.checkRoleAllowed(role)
        roleService.checkRoleDataScope(role.roleId)
        if (!roleService.checkRoleNameUnique(role)) {
            return error("修改角色'" + role.roleName + "'失败，角色名称已存在")
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return error("修改角色'" + role.roleName + "'失败，角色权限已存在")
        }
        role.updateBy=username
        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            val loginUser: LoginUser = loginUser
            if (MyStringUtils.isNotNull(loginUser.user) && !loginUser.user?.isAdmin!!) {
                loginUser.permissions=(permissionService.getMenuPermission(loginUser.user))
                loginUser.user=(userService.selectUserByUserName(loginUser.user!!.userName))
                tokenService.setLoginUser(loginUser)
            }
            return success()
        }
        return error("修改角色'" + role.roleName + "'失败，请联系管理员")
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    open  fun dataScope(@RequestBody role: SysRole): AjaxResult {
        roleService.checkRoleAllowed(role)
        roleService.checkRoleDataScope(role.roleId)
        return toAjax(roleService.authDataScope(role))
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    open fun changeStatus(@RequestBody role: SysRole): AjaxResult {
        roleService.checkRoleAllowed(role)
        roleService.checkRoleDataScope(role.roleId)
        role.updateBy=username
        return toAjax(roleService.updateRoleStatus(role))
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    open fun remove(@PathVariable roleIds: Array<Long>?): AjaxResult {
        return toAjax(roleService.deleteRoleByIds(roleIds))
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    open fun optionselect(): AjaxResult {
        return success(roleService.selectRoleAll())
    }

    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/allocatedList")
    open fun allocatedList(user: SysUser): TableDataInfo {
        startPage()
        val list = userService.selectAllocatedList(user)
        return getDataTable(list)
    }

    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/unallocatedList")
    open fun unallocatedList(user: SysUser?): TableDataInfo {
        startPage()
        val list= userService.selectUnallocatedList(user)
        return getDataTable(list)
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    open fun cancelAuthUser(@RequestBody userRole: SysUserRole?): AjaxResult {
        return toAjax(roleService.deleteAuthUser(userRole))
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    open fun cancelAuthUserAll(roleId: Long?, userIds: Array<Long>?): AjaxResult {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds))
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    open fun selectAuthUserAll(roleId: Long?, userIds: Array<Long>?): AjaxResult {
        roleService.checkRoleDataScope(roleId)
        return toAjax(roleService.insertAuthUsers(roleId, userIds))
    }

    /**
     * 获取对应角色部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = ["/deptTree/{roleId}"])
    open fun deptTree(@PathVariable("roleId") roleId: Long?): AjaxResult {
        val ajax: AjaxResult = AjaxResult.success()
        ajax["checkedKeys"] = deptService.selectDeptListByRoleId(roleId)
        ajax["depts"] = deptService.selectDeptTreeList(SysDept())
        return ajax
    }
}
